<!--  -->
<template>
  <div>
    <Header title="社会组织评估申报平台" background="#fff"></Header>
    <div class="bg">
      <div class="title">
        <div>社会组织评估申报平台</div>
        <span class="apply" @click="toApply">申报入口&nbsp;></span>
      </div>
    </div>
    <div class="content" :style="{ paddingBottom: picUrlList.length ? '38px' : '132px' }">
      <Horizontal v-if="!picUrlList.length" @more="handleClick" />
      <Vertical v-else @more="handleClick"></Vertical>
    </div>
    <div class="consult">
      <div
        class="kf"
        @mouseover="handleMouseOver('wechat')"
        @mouseout="handleMouseOut"
      >
        <img src="@/assets/wechat.png" alt="" />
        <div style="line-height: 30px; border-bottom: 1px solid #d0d0d0">
          小程序
        </div>
      </div>
      <div
        class="kf"
        @mouseover="handleMouseOver('qq')"
        @mouseout="handleMouseOut"
      >
        <img src="@/assets/qq.png" alt="" />
        <div style="line-height: 30px; border-bottom: 1px solid #d0d0d0">
          QQ
        </div>
      </div>
      <div class="kf" @click="showKf">
        <img src="@/assets/kf.png" alt="" />
        <div style="line-height: 30px">在线咨询</div>
      </div>
    </div>
    <div class="mask" v-if="visible">
      <div>
        <div class="top">
          <div>咨询服务</div>
          <a-icon type="close" @click="visible = false" />
        </div>
        <div class="context_container" ref="context_container">
          <div class="artificial_intelligence">
            <img src="@/assets/kefu.png" />
            <span class=""> 人工智能 </span>
            <span class="">
              {{ $moment().format("YYYY-MM-DD HH:mm:ss") }}
            </span>
          </div>
          <div class="context">
            <div class="context_tips">
              您好，欢迎方位社会组织申报评估 小程序！我是小爱，很高兴为您服 务！
            </div>
            <div class="" @click="handleSearch('如何咨询')">如何咨询</div>
            <div class="" @click="handleSearch('怎么上传资料')">
              怎么上传资料
            </div>
            <div class="" @click="handleSearch('转人工客服')">转人工客服</div>
          </div>
          <div
            class="que_ans"
            v-for="(item, index) in questionAndAnswesList"
            :key="index"
          >
            <div
              class="que_ans_info"
              :style="{
                display: 'flex',
                justifyContent: item.tag === 'my' ? 'flex-end' : 'flex-start',
                alignItems: 'center',
              }"
            >
              <img :src="item.url" v-if="item.tag !== 'my'" />
              <div>
                {{ item.name }}
              </div>
              <div class="">{{ item.time }}</div>
            </div>
            <div :class="item.tag === 'my' ? 'my' : 'robot'">
              <div class="content">
                <div style="margin-bottom: 5px">{{ item.content }}</div>
                <div class="" style="text-align: center">
                  <img
                    v-if="item.img"
                    class=""
                    :src="item.img"
                    style="width: 197px; height: 197px; margin-top: 20px"
                  />
                </div>
                <div v-if="item.tag !== 'my'&&Object.keys(item.file).length" class="attachment">
                  <div class="attachment_reply">此答复包含附件</div>
                  <div class="attachment_btn">
                    <a-button type="primary" ghost @click="handlePreview(item.file)"
                      >查看</a-button
                    ><a-button
                      type="primary"
                      ghost
                      style="margin-left: 20px"
                      @click="handleUpload(item.file)"
                      >下载</a-button
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="search">
          <a-input v-model="keyword"></a-input
          ><span @click="handleSearch(keyword)">发送</span>
        </div>
      </div>
    </div>
    <div v-if="hoverText" :class="hoverText == 'wechat' ? 'wechat' : 'qq'">
      <img :src="imgUrl" alt="" />
    </div>
    <a-modal
      title="word预览"
      :width="1000"
      :visible="previewVisible"
      :footer="null"
      @cancel="
        () => {
          previewVisible = false;
        }
      "
    >
      <div class="home">
        <div ref="file"></div>
      </div>
    </a-modal>
    <a-modal
      title="pdf预览"
      :width="1000"
      :visible="pdfPreviewVisible"
      :footer="null"
      @cancel="
        () => {
          pdfPreviewVisible = false;
        }
      "
    >
      <pdf v-for="i in numPages" :key="i" :page="i" :src="pdfUrl" ref="pdf"></pdf>
    </a-modal>
    <a-modal
      title="图片预览"
      :width="640"
      :visible="picPreviewVisible"
      :footer="null"
      @cancel="
        () => {
          picPreviewVisible = false;
        }
      "
    >
      <img :src="picUrl" style="width: 100%;height:auto;" />
    </a-modal>
  </div>
</template>
<script>
import Horizontal from "./horizontal";
import Vertical from "./vertical";
import Header from "@/components/header";
import { getDeclarationSystem, isReported, pageList } from "@/api";
import { quickReply, getLeaveMessageList } from "@/api/home";
import { getInfo } from "@/api/login";
import axios from "axios";
const docx = require("docx-preview");
import pdf from "vue-pdf";
export default {
  data() {
    return {
      keyword: "", // 搜索关键字
      picUrlList: [], // 图片地址
      visible: false, // 咨询弹窗
      questionAndAnswesList: [], // 问题与回复列表
      token: "",
      userInfo: {},
      currentDeclarationObj: {},
      currentDeclaration: "",
      currentDeclarationId: "",
      imgUrl: "",
      hoverText: "",
      userName: "",
      previewVisible: false, // 预览word pic
      pdfUrl: "",
      pdfPreviewVisible: false,
      picPreviewVisible: false,
      picUrl: "",
      numPages: null,
    };
  },
  created() {
    this.token = this.$storejs.get("token");
    this.userInfo = this.$storejs.get("userInfo");
    /**
     * 有token的时候再进行接口获取数据
     * to范哥
     */
    if (this.token) this.getDeclarationId();
  },
  mounted() {
    this.loadScript()
    /**
     * 有token的时候再进行接口获取数据1
     * to范哥
     */
    let userInfo = this.$storejs.get("userInfo") || ''
    console.log('userinfo', userInfo);
    if (!userInfo) {
      this.getUserInfo()
    } else {
      this.userName = this.$storejs.get("userInfo").user.userName;
    }
    if (this.token) this.getPageList();
    if (this.token) this.getLeaveMessageList();
  },
  methods: {
    loadScript() {
      let isLoadScript = sessionStorage.getItem('isLoadScript')
      if (!isLoadScript) {
        sessionStorage.setItem('isLoadScript', '1')
        location.reload()
        return;
      }
   
      
      let scripts = document.getElementsByTagName('script');
      for (let i = scripts.length; i--;) {
        if (scripts[i].src == 'https://kb.jiuseai.com/api/application/embed?protocol=https&host=kb.jiuseai.com&token=031ebe7bc43d0b43') {
          console.log('已经加载js');
          return;
        }
      }

      // 创建脚本标签 加载脚本
      let script = document.createElement('script')
      script.src = 'https://kb.jiuseai.com/api/application/embed?protocol=https&host=kb.jiuseai.com&token=031ebe7bc43d0b43'
      script.type = "text/javascript";
      script.async = true
      script.defer = true
      document.head.appendChild(script)
      script.onload = function () {
        console.log('js资源已加载成功了')
      }
      script.onerror = function () {
        console.log('js资源加载失败了')
      }
    },
    getUserInfo() {
      getInfo({}).then((res) => {
        this.$storejs.set("userInfo", res.data);
        this.userName = res.data.user?.nickName || ''
      });
    },
    getLeaveMessageList() {
      getLeaveMessageList({
        size: 9999,
        current: 1,
        type: 2,
      }).then((res) => {
        res.data.records.forEach((item) => {
          this.questionAndAnswesList.push({
            time: item.createTime,
            name: this.userName || "我",
            content: item.message,
            tag: "my",
          });
          if (item.leaveMessageReplyList && item.leaveMessageReplyList.length) {
            item.leaveMessageReplyList.forEach((message) => {
              this.questionAndAnswesList.push({
                time: item.replyTime,
                name: "人工智能",
                file: message.fileUrl ? message : {},
                content: message.reply,
                url: require("@/assets/kefu.png"),
              });
            });
          } else {
            this.questionAndAnswesList.push({
              time: item.createTime,
              name: "人工智能",
              content: "转人工客服",
              file: {},
              img: require("@/assets/qq.jpg"),
              url: require("@/assets/kefu.png"),
            });
          }
        });
      });
    },
    // 通知公告
    getPageList() {
      pageList({ size: 9999, current: 1, type: 1 }).then((res) => {
        if (res.data.records && res.data.records.length) {
          if (res.data.records.length >= 5) {
            res.data.records.slice(0, 5).forEach((item) => {
              this.picUrlList.push(item);
            });
          } else {
            res.data.records.forEach((item) => {
              this.picUrlList.push(item);
            });
          }
        }
      });
    },
    getDeclarationId() {
      getDeclarationSystem().then((res) => {
        this.currentDeclarationObj = res.data || {};
        this.currentDeclaration = res.data ? res.data.name : "";
        this.currentDeclarationId = res.data ? res.data.id : "";
        this.$storejs.set("declarationSystemId", res.data ? res.data.id : "");
        this.$storejs.set("declarationSystem", res.data || {});
      });
    },
    toApply() {
      if (this.token) {
        if (this.currentDeclaration) {
          if (this.userInfo.user.roles[0].roleKey == "APPLICANT") {
            if (this.currentDeclarationObj.status == 2 || this.currentDeclarationObj.status == 3) {
              isReported({
                userId: this.userInfo.user.userId,
                declarationSystemId: this.currentDeclarationId,
              }).then((res) => {
                if (res.data) {
                  
                  this.$storejs.set("enterInfo", {
                    id: res.data.id,
                    declarationSystemId: res.data.declarationSystemId,
                    declarationInfoId: res.data.id,
                    userId: res.data.userId,
                    socialOrganizationTypeId: res.data.socialOrganizationTypeId,
                  });
                  if (this.currentDeclarationObj.status == 3 && (res.data.declarationLevel === '5A' || (res.data.declarationLevel === '4A' && (this.userInfo.user.phonenumber === '18921510510' || this.userInfo.user.phonenumber === '13951588010')))) {
                    this.$router.push("/apply");
                    return
                  }
                  if (res.data.status == 1) {
                    this.$message.warning("当前体系申报正在审核中，请耐心等待");
                  } else if (res.data.status == 2) {
                    this.$message.warning({
                      content: "当前体系申报审核未成功，请重新填写",
                      duration: 1.5,
                    });
                    setTimeout(() => {
                      this.$router.push({ path: "/entry", query: { id: 1 } });
                    }, 1500);
                  } else if (res.data.status == 3) {
                    this.$router.push("/apply");
                  }
                } else {
                  this.$router.push("/entry");
                }
              });
            } else if (this.currentDeclarationObj.status == 1) {
              this.$message.warning("填报还未开始");
            }else if (this.currentDeclarationObj.status == 4) {
              this.$message.warning("分数公示期，不允许申报");
            } else if (this.currentDeclarationObj.status == 5) {
              this.$message.warning("该申报已经结束");
            }
            // else if (this.currentDeclarationObj.status == 3) {
            //   this.$message.warning("专家评审中，不允许申报");
            // } 
          } else {
            this.$message.warning("当前用户角色不能申报");
          }
        } else {
          this.$message.warning("暂无申报体系，不可填报");
        }
      } else {
        this.$router.push("/index");
      }
    },
    handleClick(val) {
      if (val === "notice") {
        console.log("notice");
        this.$router.push("/trends");
      } else if (val === "materials") {
        console.log("materials");
        this.$router.push("/guide");
      } else {
        console.log("result");
        this.$router.push("/result");
      }
    },
    handleSearch(val) {
      if (!val) return this.$message.error("搜索内容不可为空");
      this.handleSend(val);
    },
    // 发送
    handleSend(val) {
      // console.log(val);
      this.questionAndAnswesList.push({
        time: this.$moment().format("YYYY-MM-DD HH:mm:ss"),
        name: this.userName || "我",
        content: val,
        tag: "my",
      });
      quickReply({
        keyWord: val,
      }).then((res) => {
        // console.log("res===", res);
        if (res.data.length) {
          res.data.forEach((item) => {
            this.questionAndAnswesList.push({
              time: this.$moment().format("YYYY-DD-MM HH:mm:ss"),
              name: "人工智能",
              file: item.file && Object.keys(item.file).length ? item.file : {},
              content: item.replyContent,
              url: require("@/assets/kefu.png"),
            });
          });
          this.$nextTick(() => {
            this.$refs.context_container.scrollTo({
              top: this.$refs.context_container.scrollHeight,
              // top: 999999999,
              behavior: "smooth",
            });
          });
        } else {
          this.questionAndAnswesList.push({
            time: new Date().getTime(),
            name: "人工智能",
            content: "扫码进群,可获得人工客服",
            file: {},
            img: require("@/assets/qq.jpg"),
            url: require("@/assets/kefu.png"),
          });
          this.$nextTick(() => {
            this.$refs.context_container.scrollTo({
              top: this.$refs.context_container.scrollHeight,
              behavior: "smooth",
            });
          });
        }
      });
      this.keyword = "";
    },
    handleMouseOver(val) {
      this.hoverText = val;
      if (val == "wechat") {
        this.imgUrl = require("@/assets/wechat.jpg");
      } else if (val == "qq") {
        this.imgUrl = require("@/assets/qq.jpg");
      }
    },
    handleMouseOut() {
      this.hoverText = "";
      this.imgUrl = "";
    },
    // 查看附件
    handlePreview(file) {
      const url = file.fileUrl || file.url;
      if (url.includes("docx")) {
        this.previewVisible = true;
        axios({
          method: "get",
          responseType: "blob", // 设置响应文件格式
          url,
        }).then(({ data }) => {
          docx.renderAsync(data, this.$refs.file); // 渲染到页面预览
        });
      } else if (url.includes("pdf")) {
        this.pdfUrl = pdf.createLoadingTask({
          url,
          withCredentials: false,
        });
        this.pdfUrl.promise
          .then((pdf) => {
            this.numPages = pdf.numPages;
            console.log(this.numPages);
          })
          .catch((err) => {
            console.error("pdf 加载失败", err);
          });
        this.pdfPreviewVisible = true;
      } else {
        this.picUrl = url;
        this.picPreviewVisible = true;
      }
      // window.open(file.url, "_blank");
    },
    // 下载附件
    handleUpload(file) {
      const url = file.fileUrl || file.url;
      if (url.includes("docx") || url.includes("pdf")) {
        let link = document.createElement("a");
        //创建一个a标签
        link.style.display = "none";
        //将a标签隐藏
        link.href = url;
        //给a标签添加下载链接  "域名+接口"  safe是一个动态的域名  后面的接口替换成你自己的下载接口
        link.setAttribute("download", file.original);
        // 此处注意，要给a标签添加一个download属性，属性值就是文件名称 否则下载出来的文件是没有属性的，空白白
        document.body.appendChild(link);
        //将上面创建的a标签加入到body的尾部
        link.click();
      } else {
        let image = new Image();
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function () {
          let canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          let context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          let url = canvas.toDataURL("image/png");
          let a = document.createElement("a");
          let event = new MouseEvent("click");
          a.download = file.original;
          a.href = url;
          a.dispatchEvent(event);
        };
        image.src = url;
      }
    },
    showKf() {
      let documents = document.getElementsByClassName('maxkb-chat-button')
      if (documents && documents.length > 0) {
        document.getElementsByClassName('maxkb-chat-button')[0].click()
      }
      // this.visible = true;
      // this.$nextTick(() => {
      //   this.$refs.context_container.scrollTo({
      //     top: this.$refs.context_container.scrollHeight,
      //     // behavior: "smooth",
      //   });
      // });
    },
  },
  components: { Horizontal, Vertical, Header, pdf }
};
</script>
<style lang="less" scoped>
.bg {
  background: url("~@/assets/home_bg.png") no-repeat 0 0;
  background-size: 100% 100%;
  height: 38vh;
  padding: 13vh 0 0 9vw;
  .title {
    font-size: 48px;
    color: #fff;

    div {
      font-size: 48px;
      height: 49px;
      margin-bottom: 3vh;
    }
    .apply {
      cursor: pointer;
      display: inline-block;
      // width: 164px;
      line-height: 54px;
      color: #fff;
      padding-left: 30px;
      padding-right: 30px;
      background: #e97c34;
      font-size: 20px;
      border: 3px solid #f9bd8e;
      border-radius: 27px;
    }
  }
}
.content {
  padding: 59px 9vw 0;
}
.consult {
  position: fixed;
  right: 35px;
  bottom: 20vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 0 10px #ccc;
  background: #ffffff;
  cursor: pointer;
  .kf {
    // width: 100px;
    // height: 100px;
    text-align: center;
    padding: 10px 10px;
    // line-height: 100px;
    border-radius: 4px;
    // margin-bottom: 15px;
    img {
      width: 36px;
      height: 36px;
    }
  }
}
.mask {
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.65);
  font-size: 16px;
  & > div {
    position: absolute;
    background: #f2f2f2;
    bottom: 78px;
    right: 126px;
    border-radius: 4px;
    width: 28vw;
    height: 64vh;
    .top {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 29px 0 37px;
      line-height: 63px;
      color: #000;
      font-weight: bold;
      border-bottom: 1px solid #dcdcdc;
    }
    .context_container {
      padding: 28px 38px 0;
      overflow-y: scroll;
      height: calc(64vh - 82px - 56px - 15px);
      .artificial_intelligence {
        font-size: 14px;
        display: flex;
        align-items: center;
        img {
          width: 48px;
          height: 48px;
        }
        span {
          margin-left: 13px;
          color: #666;
        }
      }
      .context {
        // width: 282px;
        margin-left: 62px;
        background: #fff;
        padding: 22px 25px 21px 17px;
        color: #1481ff;
        border-radius: 16px;
        border-top-left-radius: 0;
        .context_tips {
          line-height: 24px;
          font-size: 16px;
          color: #4a4a4a;
        }
        div {
          color: #1481ff;
          font-size: 26rpx;

          &:nth-child(n + 2) {
            margin-top: 20px;
            cursor: pointer;
          }
        }
      }
      .que_ans {
        margin-top: 43px;
        .que_ans_info {
          color: #666;
          font-size: 14px;
          img {
            width: 48px;
            height: 48px;
          }
          div {
            &:nth-child(n + 1) {
              margin-left: 10px;
            }
          }
        }
        .my {
          display: flex;
          justify-content: flex-end;
          .content {
            margin-top: 16px;
            background: linear-gradient(90deg, #417ffc, #505eeb);
            box-shadow: 0px 6px 10px 0px rgba(22, 121, 253, 0.28);
            padding: 0 24px 0 36px;
            line-height: 53px;
            color: #fff;
            width: 144px;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            border-radius: 27px;
            border-top-right-radius: 0;
          }
        }
        .robot {
          .content {
            // text-align: center;
            margin-top: 13px;
            background: #fff;
            padding: 16px 13px 27px;
            width: 282px;
            line-height: 24px;
            font-size: 28rpx;
            color: #4a4a4a;
            border-radius: 16px;
            border-top-left-radius: 0;
            margin-left: 62px;
          }
        }
      }
    }
    .search {
      position: fixed;
      bottom: 104px;
      right: 160px;
      left: calc(100vw - 28vw - 126px + 38px);
      ::v-deep.ant-input {
        height: 56px;
      }
      span {
        cursor: pointer;
        color: #427efc;
        position: absolute;
        right: 27px;
        bottom: 16px;
      }
    }
  }
}
.wechat,
.qq {
  position: fixed;
  right: 120px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 0 10px #ccc;
  padding: 10px;
  width: 120px;
  height: 120px;
  background: #fff;
  img {
    width: 100px;
    height: 100px;
  }
}
.wechat,
.qq {
  bottom: 25vh;
}
.attachment {
  // margin-top: 20px;
  text-align: center;
  .attachment_reply {
    line-height: 35px;
    border-top: 1px solid #ccc;
  }
}
.home {
  width: 100%;
}

::v-deep .docx-wrapper {
  padding: none;
  background: none;
}

::v-deep .docx {
  width: auto !important;
  padding: 0px !important;
  box-shadow: none !important;
}
</style>